package com.sky.controller;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.sky.domain.Document;
import com.sky.service.DocumentService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author 尹稳健~
 * @version 1.0
 */
@Api(tags = "文档模块")
@Controller
@RequestMapping("/document")
public class DocumentController {

    @Autowired
    private DocumentService documentService;

    @GetMapping("/document")
    public Document document(){
        return new Document();
    }

    // 查询所有，包含分页查询，模糊查询
    @ApiOperation("查询所有,模糊查询")
    @GetMapping("/list")
    public String findAll(@RequestParam(value = "content",defaultValue = "") String title,
                          @RequestParam(value = "pn",defaultValue = "1") Integer pn,
                          Model model){
        PageHelper.startPage(pn,5);
        List<Document> documentList = documentService.findAll(title);
        PageInfo<Document> pageInfo = new PageInfo<>(documentList);
        model.addAttribute("pageInfo",pageInfo);
        return "/document/list";
    }

    @ApiOperation("跳转更新/添加页面")
    @GetMapping("/upload")
    public String toUploadPage(Integer id,Model model){
        if (id != null) {
            // 跳转更新页面 将数据进行回显
            Document document = documentService.findDocumentById(id);
            model.addAttribute("document",document);
            model.addAttribute("msg","1");
        }else{
            // 跳转添加页面
            model.addAttribute("msg","0");
        }
        return "/document/add";
    }

    @ApiOperation("更新/添加操作")
    @PostMapping("/upload")
    public String upload(Document document) throws IOException {
        if (document.getId() != null){
            // 更新操作
            documentService.update(document);
        }else{
            // 添加操作
            String originalFilename = document.getFile().getOriginalFilename();
            document.getFile().transferTo(new File("E:\\upload\\"+UUID.randomUUID()+originalFilename));
            documentService.upload(document);
        }
        return "redirect:/document/list";
    }

    @ApiOperation("删除")
    @GetMapping("/delete")
    public String delete(Integer id){
        documentService.delete(id);
        return "redirect:/document/list";
    }
}
